package com.showsu.editor.utils.remote;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.URLUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.showsu.editor.entity.tikhub.TikhubXhsAwemeCommentListData;
import com.showsu.editor.entity.tikhub.TikhubXhsAwemeCommentListResp;
import com.showsu.editor.enums.SuccessEnum;
import com.showsu.editor.service.IRemoteInterfaceRecordService;
import com.showsu.editor.service.IRemoteInterfaceWarnSmsRecordService;
import com.showsu.editor.utils.GsonFailSafeArrayJsonDeserializer;
import com.showsu.editor.utils.HttpClientUtil;
import com.showsu.editor.utils.RetryUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;

/**
 * @Author: William
 * @Description: 接口文档：https://apiserver.gitbook.io/apiserverdocs
 * @Date: Created in 16:41 2025/4/7
 * @Modified By:
 */
@Slf4j
@Component
public class ApiServerUtil {

    /**
     * gson反序列化时，用于忽略array的错误。因为有的时候字段返回为空，我们认为是可以接受的。
     */
    private GsonFailSafeArrayJsonDeserializer gsonFailSafeArrayJsonDeserializer = new GsonFailSafeArrayJsonDeserializer();

    private static final int timeout = 30000;

    /**
     * 最多重试次数
     */
    private static final int RETRY_MAX_COUNT = 3;

    /**
     * 重试等待间隔
     */
    private static final int RETRY_WAIT_TIME = 1500;

    @Value("${apiServer.url}")
    private String baseUrl;

    @Value("${apiServer.token}")
    private String token;

    @Autowired
    private IRemoteInterfaceRecordService remoteInterfaceRecordService;

    @Autowired
    private IRemoteInterfaceWarnSmsRecordService remoteInterfaceWarnSmsRecordService;

    /**
     * 获取xhs笔记评论数据（带live）
     * @param noteId
     * @param cursor 首页传空，翻页是用上一页的最后一个评论id
     * @param interfaceId
     * @return
     */
    public TikhubXhsAwemeCommentListResp getXhsAwemeCommentList(String noteId, String cursor, Long interfaceId) {
        if (StringUtils.isBlank(noteId)) {
            return null;
        }
        Type type = new TypeToken<TikhubXhsAwemeCommentListData>(){}.getType();
        Gson gson = new Gson();
        TikhubXhsAwemeCommentListResp result = new TikhubXhsAwemeCommentListResp();

        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", token);
        headers.put("Content-Type", "application/json");

        String response = RetryUtils.retry(new Callable<String>() {
            @Override
            public String call() {
                try {
                    long start = System.currentTimeMillis();
                    StringBuilder url = new StringBuilder(baseUrl).append("/api/xhs/getcomment?noteId=").append(noteId).append("&start=").append(cursor);
                    String responseInner = HttpClientUtil.get(url.toString(), null, headers, timeout);
                    log.info("ApiServerUtil查询xhs笔记评论列表,响应耗时:{},noteId:{},start:{}", System.currentTimeMillis() - start, noteId, cursor);
                    if (StringUtils.isBlank(responseInner)) {
                        return "";
                    }
                    JSONObject jsonObject = JSON.parseObject(responseInner);
                    if (jsonObject == null || jsonObject.get("data") == null) {
                        remoteInterfaceRecordService.add(interfaceId, SuccessEnum.FAIL.getCode());
                        return "";
                    }

                    TikhubXhsAwemeCommentListData temp = gson.fromJson(jsonObject.getString("data"), type);
                    //如果平台那边报错再重试一次
                    if (temp == null || (temp.getCode() != null && temp.getCode().intValue() != 0)) {
                        remoteInterfaceRecordService.add(interfaceId, SuccessEnum.FAIL.getCode());
                        return "";
                    }
                    remoteInterfaceRecordService.add(interfaceId, SuccessEnum.SUCCESS.getCode());
                    return jsonObject.getString("data");
                } catch (Exception e) {
                    remoteInterfaceRecordService.add(interfaceId, SuccessEnum.FAIL.getCode());
                    log.error("ApiServerUtil.getXhsAwemeCommentList(String,String,Long) error, noteId:{}, start:{}, e:{}", noteId, cursor, e);
                    return "";
                }
            }
        }, RETRY_MAX_COUNT, RETRY_WAIT_TIME);
        if (StringUtils.isBlank(response)) {
            remoteInterfaceWarnSmsRecordService.sendWarnSmsIn15mins(interfaceId,
                    new StringBuilder("noteId=").append(noteId).append(",cursor=").append(cursor).toString());
            return result;
        }
        try {
            TikhubXhsAwemeCommentListData tikhubXhsAwemeCommentListData = gson.fromJson(response, type);
            tikhubXhsAwemeCommentListData.initVideoInfo();
            //这个接口要把最后一条评论的id作为下一页请求的start
            if (tikhubXhsAwemeCommentListData.getData() != null && ! CollectionUtils.isEmpty(tikhubXhsAwemeCommentListData.getData().getComments())) {
                tikhubXhsAwemeCommentListData.getData().setCursor(
                        tikhubXhsAwemeCommentListData.getData().getComments().get(
                                tikhubXhsAwemeCommentListData.getData().getComments().size() - 1
                        ).getId());
            }
            result.setData(tikhubXhsAwemeCommentListData);
        } catch (Exception e) {
            log.error("ApiServerUtil.getXhsAwemeCommentList(String) convert error, noteId:{}, start:{}, e:{}", noteId, cursor, e);
        }
        return result;
    }

    public static void main(String[] args) {
    }

}
